package com.huluobo.a2203kotlinjetpackdemo.paging

import android.content.Context
import android.net.ConnectivityManager
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator

/**
 *  Created by LC on 2024/7/23.
 */
@OptIn(ExperimentalPagingApi::class)
class RepoMediator(val api: ApiService, val db: AppDatabase, val context: Context) : RemoteMediator<Int, Bean>() {
    override suspend fun load(loadType: LoadType, state: PagingState<Int, Bean>): MediatorResult {
        val beanDao = db.getBeanDao()

        //当需要加载页面时,读取状态中来判断是否给页码赋值
        val pageKey = when (loadType) {
            //首次访问,或者调用pageAdapter.refresh的时候
            LoadType.REFRESH -> null
            //在当前加载的数据集和开头加载数据时,endOfPaginationReached 代表没有更多数据了
            LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
            //上拉加载更多的时候
            LoadType.APPEND -> {
                val lastItem = state.lastItemOrNull() ?: return MediatorResult.Success(
                    endOfPaginationReached = true
                )
                lastItem.page
            }
        }

        //无网络则加载本地数据
        if (!isConnectedNetWork()) {
            return MediatorResult.Success(true)
        }

        //有网状态加载网络分页数据
        val page = pageKey ?: 1 //当前的页码
        val pageSize = Repo.PAGE_SIZE//当前页面中item的数量
        val result = api.searchRepos(page, pageSize).items //发起网络请求的返回
        val endOfPaging = result.isEmpty()
        val items = result.map {
            Bean(
                id = it.id,
                name = it.name,
                description = it.description,
                stargazers_count = it.stargazers_count,
                page = it.page + 1,
                language = it.language
            )
        }

        if (loadType == LoadType.REFRESH) {
            beanDao.clear()
        }
        beanDao.insert(items)
        return MediatorResult.Success(endOfPaginationReached = endOfPaging)
    }

    private fun isConnectedNetWork(): Boolean {
        val connectManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetworkInfo = connectManager.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnected
    }
}